﻿
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Text.Json;
using ValidationException = MeetingRoomBooking.Application.Common.Exceptions.ValidationException;

namespace MeetingRoomBooking.Application.Common.Middlewares;

public class ExceptionHandlingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionHandlingMiddleware> _logger;

    public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        var response = context.Response;

        switch (exception)
        {
            case ValidationException validationException:
                response.StatusCode = (int)HttpStatusCode.BadRequest;
                var validationResult = new
                {
                    message = validationException.Message,
                    errors = validationException.Errors 
                };
                _logger.LogWarning("Validation failed: {Message} {Errors}", validationException.Message, validationException.Errors);
                await context.Response.WriteAsync(JsonSerializer.Serialize(validationResult));
                break;

            default:
                response.StatusCode = (int)HttpStatusCode.InternalServerError;
                var errorResult = new
                {
                    message = "An unexpected error occurred.",
                    detail = exception.Message 
                };
                _logger.LogError(exception, "An unexpected error occurred: {Message}", exception.Message);
                await context.Response.WriteAsync(JsonSerializer.Serialize(errorResult));
                break;
        }
    }
}


public static class ExceptionHandlingMiddlewareExtensions
{
    public static IApplicationBuilder UseExceptionHandling(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ExceptionHandlingMiddleware>();
    }
}
